#手动匹配检测
import aircv as ac
import cv2
import numpy as np
import Comment
from PIL import Image

#匹配图片
def matchImgs(imgsrc,imgobj,confidencevalue=0.5):#imgsrc=原始图像，imgobj=待查找的图片
    imsrc = ac.imread(imgsrc)
    #imsrc = cv2.imread(imgsrc)
    imobj = ac.imread(imgobj)
    #imobj = cv2.imread(imgobj)
    #cv2.imshow('srcImage', imsrc)
    #cv2.waitKey(0)
    #exit()
    match_result = ac.find_all_template(imsrc,imobj,confidencevalue)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}

    return match_result
#匹配图片
def matchImg(imgsrc,imgobj,confidencevalue=0.7):#imgsrc=原始图像，imgobj=待查找的图片
    #print(imgsrc)
    #exit()
    imsrc = ac.imread(imgsrc)
    imobj = ac.imread(imgobj)
    match_result = ac.find_template(imsrc,imobj,confidencevalue)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    return match_result
#格式化浮点坐标为int坐标  
def formatPos(pos):
    x,y = pos
    posx = int(x)
    posy = int(y)
    res = (posx,posy)
    return res
def imgGray(t1):
    img = Image.open(t1)
    Img = img.convert('L')
    Img.save(t1)
    #imsrc = cv2.imread(t1)
    #cv2.imshow('srcImage', imsrc)
    #cv2.waitKey(0)
    #exit()
shotPath = 'G:\python\img';
shot=1
while shot:
    shot = Comment.screenShot(shotPath);
    #图片地址
    t1 = r'G:\python\img\tmp.jpg'
    #应用图
    t2 =  r'G:\python\money\sms\open.png'

   # imgGray(t2)
    #查找相关图片并返回坐标
    result = matchImgs(t1,t2)
    print(result)
    #exit()
    #res= [result]
    if result:  
        for k in result:
            x,y = k['result']
            k2 = (x,y)
            #Comment.tap_screen(x,y)
            #exit()
            print(k2)
            #格式化坐标
            pos = formatPos(k2)
            img = cv2.imread(t1)
            # 画一个填充红色的圆，参数2：圆心坐标，参数3：半径
            cv2.circle(img,pos, 63, (0, 0, 255), 8)
            cv2.namedWindow("Image",cv2.WINDOW_NORMAL) #创建窗口并且设置为自动调整窗口
            cv2.imshow('Image', img)  #显示图像,窗口会自动调整图像大小.第一个参数是窗口的名字,第二个才是我们的图像 && 名字必须不同
           #cv2.imwrite(t1,img)
            cv2.waitKey (0)#0无限等待键盘输入
        exit()
    else:
        #Comment.swipe_screen(718,1367,335,1367,800)
        print('未匹配到图片')
        exit()
   
    
